package net.togogo.egouweb1238.core.service.pagestatic;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;

import javax.servlet.ServletContext;

import org.springframework.stereotype.Service;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import freemarker.template.Configuration;
import freemarker.template.Template;

/**
 * 生成静态页实现类
 * @author stone
 *
 */
@Service(value = "pageStaticService")
public class PageStaticServiceImpl implements IPageStaticService, ServletContextAware {

	//静态化方法
	public void productDetail(Map<String, Object> root, Integer id) {
		//第一步:实例化Freemarker的配置类
		Configuration conf = new Configuration();
		Writer out = null;
		try{
			//第二步:给配置类设置模板路径   
			String sourceDir = getPath("/ftl/");
			conf.setDirectoryForTemplateLoading(new File(sourceDir));

			Template template = conf.getTemplate("productDetail.html");

			//第三步:处理模板及数据之间 关系 将数据与模板合成一个html
			//第四步: 输出html
			String destDir = getPath("/html/product/");
			File destFileDir = new File(destDir);
			if(!destFileDir.exists()){
				destFileDir.mkdirs();
			}
			out = new FileWriter(new File(destDir +  id + ".html"));
			//执行生成
			template.process(root, out);
			out.flush();
		}catch(Exception ex){
			ex.printStackTrace();
		}finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		

		/*Configuration conf = new Configuration();
		//输出流   从内存写出去  磁盘上
		Writer out = null;
		try {
			String fileName = getPath("/ftl/productDetail.html");
			//读进来  UTF-8  内存中
			Template template = conf.getTemplate(fileName);
			//获取Html的路径
			String path = getPath("/html/product/" + id + ".html");//252.html,253.html

			File f = new File(path);
			File parentFile = f.getParentFile();
			if (!parentFile.exists()) {
				parentFile.mkdirs();
			}
			//输出流
			out = new OutputStreamWriter(new FileOutputStream(f), "UTF-8");
			//处理模板
			template.process(root, out);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}*/
	}

	//获取路径
	public String getPath(String name) {
		return servletContext.getRealPath(name);
	}

	private ServletContext servletContext;

	@Override
	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;
	}
}
